package org.brisling.mobile.service;

import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.RetDomain;
import org.brisling.common.util.Encodes;
import org.brisling.common.util.MapUtil;
import org.brisling.medical.domain.MedicalInpatient;
import org.brisling.medical.queryService.QueryInpatientService;
import org.brisling.mobile.config.MDomain;
import org.brisling.mobile.config.RSAConfig;
import org.brisling.mobile.service.base.AbstractBaseMobileService;
import org.brisling.mobile.vo.satis.VOSubject;
import org.brisling.mobile.vo.sysman.VODept;
import org.brisling.satisfaction.domain.SatisfactionEvaluateMessage;
import org.brisling.satisfaction.domain.SatisfactionEvaluateResult;
import org.brisling.satisfaction.queryService.QuerySatisfactionEvaluateResultService;
import org.brisling.satisfaction.queryService.QuerySatisfactionEvaluateSubjectService;
import org.brisling.satisfaction.service.SatisfactionEvaluateMessageService;
import org.brisling.satisfaction.service.SatisfactionEvaluateResultService;
import org.brisling.sysman.domain.UploadFiles;
import org.brisling.sysman.domain.VersionDomain;
import org.brisling.sysman.queryService.QueryDeptService;
import org.brisling.sysman.queryService.QueryUploadService;
import org.brisling.sysman.queryService.QueryVersionService;
import org.brisling.sysman.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * <p>Title: MobileService</p>
 * <p>Description: 通用入口服务类</p>
 * <p>Company: 长沙东勤信息科技发展有限公司</p>
 * @author jackson wang
 * @since 1.0
 * @version 1.0
 * @date 2017年5月13日 下午4:06:19
 */
@RestController
@RequestMapping("/app")
public class MobileService extends AbstractBaseMobileService{

	@Autowired
	private QueryVersionService qryVersionService;
	
	@Autowired
	private UploadService uploadService;
	
	@Autowired
	private QueryUploadService qryUploadService;
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	
	@Autowired
	private QueryInpatientService qryInpatientService;
	
	
	//住院满意度评价结果主表
	@Autowired
	private SatisfactionEvaluateMessageService semService;
	
	//住院满意度评价结果明细
	@Autowired
	private SatisfactionEvaluateResultService serService;
	
	@Autowired
	private QuerySatisfactionEvaluateResultService qryserService;
	
	
	@Autowired
	private QuerySatisfactionEvaluateSubjectService problemService;
	
	@Autowired
	private QueryDeptService qryDeptService;
	
	
	
	
	private static Map<String,VOSubject> problemMap = null;
	
	/**
	 * 
	 * 
	 * 
	 * @param path		路径
	 * @param keycode	密钥对键值代码
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getKey.m")
	public MDomain getKey(HttpServletResponse response){
		MDomain m = new MDomain();
		
		String code =RSAConfig.getInitKey();
		m.setC(code);
		Map<PublicKey,PrivateKey>  keyMap = RSAConfig.getVerifyKeyPaire(code);
		
		PublicKey key = RSAConfig.getPublicKey(keyMap);
		byte[] pb = key.getEncoded();
        String pbStr =  new String(Base64.encode(pb));
		m.setP(pbStr);		
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		return m;
	}	
	
	/**
	 * 登录系统
	 * @param mkey	密钥
	 * @param val	加密参数
	 * @return
	 */
	@RequestMapping("/lm.m")
	public MDomain login(@RequestParam(value="c",required=false) String mkey,
			@RequestParam(value="val",required=false) String val,
			HttpSession session,
			HttpServletResponse response){
		MDomain ret = new MDomain();
		response.setHeader("Access-Control-Allow-Origin", "*");
		//判断密钥及参数是否为空
		if( (mkey != null) && (val != null ) ){
			
			PrivateKey key = RSAConfig.getVerifyPrivateKey(mkey);
			
			String _data = RSAConfig.decrptData(mkey, val, false);
			
			Map<String,Object> paramMap = new HashMap<String,Object>();
			
			String userid = null;
			String site = null;
			String password = null;
			//解析数据
			if(_data!=null){
				paramMap = MapUtil.getBodyParam(_data);
				userid = MapUtil.getMapData(paramMap, "userid");
				
				site = MapUtil.getMapData(paramMap, "site");
				
				password = MapUtil.getMapData(paramMap, "password");
				
			}
			//验证用户
			
			//判断验证结果
			
			return ret;
		}
		return ret;
	}
	
	
	/**
	 * 获取版本
	 * @param platform
	 * @return
	 */
	@RequestMapping("/gv.m")
	public MDomain getVersion(@RequestParam(value="c",required=false) String mkey,
									@RequestParam(value="val",required=false) String val,
									@RequestBody(required=false) String body){
		
		MDomain d = new MDomain();
		final String platform = "platform";
		if( (mkey!=null) && (mkey.trim().length()>0) ){
			mkey = mkey.trim();
			//获取私钥
			PrivateKey priKey = RSAConfig.getVerifyPrivateKey(mkey);
			
			//获取解密数据
			if(priKey!=null){
				String _data = RSAConfig.decrptData(mkey, val, null);
				
				//解析传入参数
				if(_data!=null){
					Map<String, Object>  param = super.getBodyParam(_data);
					
					//判断参数有效性
					if(param!=null && !param.isEmpty()){
						
						param.containsKey(platform);
						Object obj = param.get(platform);
						
						if(obj!=null ){
							d.setData(qryVersionService.getLastVersion(obj.toString()));
						}
					}
				}
			}
			
			
		}
		return d;
	}
	
	
	/**
	 * 获取指定平台版本版本
	 * @param platform
	 * @return
	 */
	@RequestMapping("/gpv.m")
	public MDomain getPlatformVersion(@RequestParam(value="platform_id",required=false) String platform_id){
		MDomain d = new MDomain();
		if(platform_id!=null ){
			
			//获取平台最新版本文件
			VersionDomain v = qryVersionService.getLastVersion(platform_id);
			if( (v != null ) && (v.getId()!=null)){
				
				//根据版本文件业务编码及记录编号，查询版本文件附件编码
				Map<String,String> map = new HashMap<String,String>();
				map.put("bizcode", "version");
				map.put("bizno_in", v.getId().toString());
				List<UploadFiles> uf = qryUploadService.getList(map);
				
				//判断版本文件是否唯一
				if(uf!=null && uf.size()==1){
					
					//封装版本文件附件id，传递到前台
					UploadFiles u = uf.get(0);
					if(u!=null && u.getId()!=null){
						v.setArchiveid(u.getId());
					}
				}
			}
			d.setData(v);
		}
		return d;
	}
	
	/**
	 * 获取版本文件
	 * @param id	版本文件记录id
	 * @return
	 */
	@RequestMapping("/df.m")
	public void downloadFile(@RequestParam(value="id",required=false) Long id,HttpServletRequest request,HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		uploadService.downloadFile(id, request, response);
			
	}
	
	@RequestMapping("/getCurrentPatient.m")
	public List<MedicalInpatient> getCurrentPatient(@RequestParam(value="userid",required=false) String userid,
			@RequestParam(value="deptid",required=false) String deptid,
			HttpServletResponse response){
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> map = new HashMap<String,Object>();
		
		map.put("userid", userid);
		map.put("deptid", deptid);
			
		return qryInpatientService.getCurrentPatient(map,"query_ethic_all");
	}
	
	/**
	 * 获取当前用户管理的科室
	 * @param userid
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getCurrentDept.m")
	public List<VODept> getCurrentDept(@RequestParam(value="userid",required=false) String userid,
			
			HttpServletRequest request,
			HttpServletResponse response){
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		
			
		return qryDeptService.getCurrentUserDeptList(userid, "query_ethic_all");
	}
	
	
	/**
	 * 获取评价题目
	 * @param e_type
	 * @return
	 */
	@RequestMapping("/getProblemList.m")
	public List<VOSubject>  getProblemList(
			@RequestParam(value="e_type",required=false) String e_type,
			HttpServletResponse response){
		
		if(response!=null)
			response.setHeader("Access-Control-Allow-Origin", "*");
		return problemService.getAppList(e_type);
	
	}
	
	/**
	 * 保存评价结果
	 * @param data	待保存的评价内容
	 * @return
	 */
	@RequestMapping("/saveEvaluate.m")
	public RetDomain  saveEvaluate(
			@RequestParam(value="data",required=false) String data,
			HttpServletResponse response){
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		RetDomain domain = RetDomain.errorDomain("error");
		
		if(data == null){
			
			return domain;
			
		}else{
			data = Encodes.urlDecode(data);
			
			List<SatisfactionEvaluateResult> lists = null;					
			
			
			ObjectMapper mapper = new ObjectMapper();
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
			JavaType _javaType = mapper.getTypeFactory().constructCollectionType(List.class, SatisfactionEvaluateResult.class);
			
			try {
				lists =  mapper.readValue(data, _javaType);				
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			//缓存患者信息
			Map<String,String> miMap = new HashMap<String,String>();
			if(lists!=null){
				for(SatisfactionEvaluateResult s:lists){
					
					String patientid = null;
					if(!miMap.containsKey(s.getPatient_id())){
						//当前题目主表未保存
						
						//查询患者信息
						MedicalInpatient  mi = qryInpatientService.getOneByField("patient_id", s.getPatient_id());
												
						if(mi!=null){
							//保存评价结果主表
							SatisfactionEvaluateMessage  sem =semService.saveInpatientMessage(mi);
							miMap.put(mi.getPatient_id(), String.valueOf(sem.getId()));							
							s.setEvaluate_id(String.valueOf(sem.getId()));
						}
					}else{
						//评价结果主表已保存，取主表id
						s.setEvaluate_id(miMap.get(s.getPatient_id()));
					}
					
					//获取题目设置
					VOSubject ses = this.getProblem(s.getProblem_code());
					if(ses!=null){
						s.setProblem_subject(ses.getProblem_subject());											
					}					
					
				}				
				//缓存保存前的数据集数量
				Integer count = lists.size();
				
				lists = serService.saveResult(lists);
				
				//检查保存后数据集数量
				if(lists!=null && lists.size()==count){
					domain = RetDomain.successDomain("success");
					domain.setRows(miMap);
				}
			}		
			
		}
		return domain;
	
	}
	
	/*
	 * 根据题目代码获取题目记录
	 */
	private VOSubject getProblem(String code){
		
		VOSubject ret = null;
		
		//判断题目代码是否有效
		if(code!=null){
			
			//判断题目是否缓存
			if(problemMap==null){
				initProblem();			
			}
			
			//判断题目是否存在
			if(problemMap!=null && problemMap.containsKey(code)){
				ret = problemMap.get(code);
			}
			
		}
		return ret;
	}
	
	/**
	 * 获取评价结果
	 * @param eid	评价结果主表id
	 * @return
	 */
	@RequestMapping("/getResult.m")
	public List<SatisfactionEvaluateResult>  getResult(@RequestParam(value="patient_id",required=false) String patient_id){
		
		return qryserService.getListByIdentify("patient_id", patient_id);
	}
	
	//初始化题目缓存
	private Boolean initProblem(){
		problemMap = new HashMap<String,VOSubject>();
		
		List<VOSubject> lists = this.getProblemList("2", null);
		for(VOSubject ses:lists){
			problemMap.put(ses.getProblem_code(), ses);
		}
		return true;
	}
}
